package is.model.dao.search;

/**
 *
 * @author aspr0
 */
public class AbstractSearch
{
    protected static final String REGEX_CANVAS = ".*%s.*";
    protected static final String QUERY_CANVAS = "select * from %s where %s order by id";


    /**
     * Replaces '*' and '?' wildcards into correct regex
     *
     * @param mask
     * @return
     */
    protected static String prepareMask(String mask)
    {
        return mask.replaceAll("\\*", ".*").replaceAll("\\?", ".{1}") + ".*";
    }

    /**
     * Provides "nonemptyfield regex ? and ... and (emptyfield regexp '.*' or emptyfield is null)" statement output
     *
     * @param fields
     * @param values
     * @return
     */
    protected static String organizeRegex(String id, String[] fields, String[] values)
    {
        String delimiter = " and ";
        String canvas = "%s regexp ?";
        String emptyRegexCanvas = "(%1$s regexp '.*' or %1$s is null)";

        String query = (id.isEmpty())
                ? String.format(emptyRegexCanvas, "id") + delimiter
                : String.format(canvas, "id") + delimiter;

        for (int partNum = 0; partNum < fields.length; partNum++)
        {
            String part;

            if (values[partNum].isEmpty())
            {
                part = String.format(emptyRegexCanvas, fields[partNum]);
            }
            else
            {
                part = String.format(canvas, fields[partNum]);
            }
            query += (partNum < fields.length - 1) ? part + delimiter : part;
        }

        return query;
    }
}
